package com.example.datamanage.controller;

import com.example.datamanage.common.Result;
import com.example.datamanage.pojo.Menu;
import com.example.datamanage.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 28142
 * @description 菜单管理控制层
 * @date 2023/7/21 17:21
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    /**
     * 查找所有菜单
     * @author 杨雨盛
     * @date 2023/7/22 14:32
     * @return com.example.datamanage.common.Result
     */
    @GetMapping
    public Result findAll() {
        return Result.success(menuService.getMenus(menuService.list()));
    }


    /**
     * 根据角色查找对应菜单列表
     * @author 杨雨盛
     * @date 2023/7/22 14:25
     * @param role
     * @return com.example.datamanage.common.Result
     */
    @GetMapping("/{role}")
    public Result getRoleMenu(@PathVariable Integer role) {
        List<Menu> menuList = menuService.getRoleMenu(role);
        return Result.success(menuList);
    }

    /**
     * 给角色分配菜单
     * @author 杨雨盛
     * @date 2023/7/23 9:42
     * @param role
     * @param ids
     * @return com.example.datamanage.common.Result
     */
    @PutMapping("/{role}")
    public Result updateRoleMenu(@PathVariable Integer role,
                                 @RequestParam List<Integer> ids) {
        menuService.updateRoleMenu(role, ids);
        return Result.success();
    }

    /**
     * 添加或编辑菜单
     * @author 杨雨盛
     * @date 2023/7/23 6:23
     * @param menu
     * @return com.example.datamanage.common.Result
     */
    @PostMapping
    public Result save(@RequestBody Menu menu) {
        System.out.println(menu);
        return menuService.saveOrUpdate(menu) ? Result.success() : Result.error();
    }

    /**
     * 根据id删除菜单
     * @author 杨雨盛
     * @date 2023/7/23 6:27
     * @param id
     * @return com.example.datamanage.common.Result
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return menuService.removeById(id) ? Result.success() : Result.error();
    }

    /**
     * 根据id数组批量删除菜单
     * @author 杨雨盛
     * @date 2023/7/23 6:32
     * @param ids
     * @return com.example.datamanage.common.Result
     */
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return menuService.removeByIds(ids) ? Result.success() : Result.error();
    }
}
